文章目录
  1. 1. How to convert List to int[]?
  2. 2. How to convert int[] into List?

How to convert List to int[]?

1
2
3
4
5
6
7
8
9
//The easiest way might be using ArrayUtils in Apache Commons Lang library.
int[] array = ArrayUtils.toPrimitive(list.toArray(new Integer[0]));
//In JDK, there is no short-cut. Note that you can not use List.toArray(), because
//that will convert List to Integer[]. The correct way is following,
int[] array = new int[list.size()];
for(int i=0; i < list.size(); i++) {
array[i] = list.get(i);
}

How to convert int[] into List?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//The easiest way might still be using ArrayUtils in Apache Commons Lang library, like below.
List list = Arrays.asList(ArrayUtils.toObject(array));
//In JDK, there is no short-cut either.
int[] array = {1,2,3,4,5};
List<Integer> list = new ArrayList<Integer>();
for(int i: array) {
list.add(i);
}
/**
*
* Arrays类中的asList方法
*
* (1) 该方法对于基本数据类型的数组支持并不好,当数组是基本数据类型时不建议使用
* (2) 当使用asList()方法时,数组就和列表链接在一起了.
* 当更新其中之一时,另一个将自动获得更新。
* 注意:仅仅针对对象数组类型,基本数据类型数组不具备该特性
* (3) asList得到的数组是的没有add和remove方法的
*
* 阅读相关:通过查看Arrays类的源码可以知道,asList返回的List是Array中的实现的
* 内部类,而该类并没有定义add和remove方法.另外,为什么修改其中一个,另一个也自动
* 获得更新了,因为asList获得List实际引用的就是数组
*/
int[] a_int = { 1, 2, 3, 4 };
/* 预期输出应该是1,2,3,4,但实际上输出的仅仅是一个引用, 这里它把a_int当成了一个元素 */
List a_int_List = Arrays.asList(a_int);
/* 对象类型的数组使用asList,是我们预期的 */
Integer[] a_Integer = new Integer[] { 1, 2, 3, 4 };
List a_Integer_List = Arrays.asList(a_Integer);
文章目录
  1. 1. How to convert List to int[]?
  2. 2. How to convert int[] into List?